import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Space,
  Button,
  Tag,
  message,
  Modal,
  Form,
  InputNumber,
  Popconfirm,
  Progress,
  Tooltip,
  Typography,
  Row,
  Col,
  Statistic,
} from 'antd';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  UserOutlined,
  CalendarOutlined,
  UploadOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import { formatBytes, formatDateTime } from '../../utils/format';
import { User } from '../../types';

const { Title, Text } = Typography;

interface AssessmentResult {
  userId: number;
  username: string;
  currentStatus: number;
  isExpired: boolean;
  deadline: string;
  daysRemaining: number;
  uploadRequirementMet: boolean;
  shareRatioRequirementMet: boolean;
  currentUploaded: number;
  requiredUploaded: number;
  currentShareRatio: number;
  requiredShareRatio: number;
  assessmentResult: string;
  message: string;
}

const UserAssessment: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [assessmentUsers, setAssessmentUsers] = useState<User[]>([]);
  const [batchResults, setBatchResults] = useState<AssessmentResult[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [form] = Form.useForm();
  const [stats, setStats] = useState({
    totalAssessment: 0,
    expiringSoon: 0,
    avgProgress: 0,
  });

  useEffect(() => {
    fetchAssessmentUsers();
    calculateStats();
  }, []);

  const fetchAssessmentUsers = async () => {
    try {
      setLoading(true);
      // 这里应该调用API获取考核期用户
      // const response = await getAssessmentUsers();
      // setAssessmentUsers(response.data);
      
      // 模拟数据
      const mockUsers: User[] = [
        {
          id: 1,
          username: 'newuser1',
          email: 'newuser1@example.com',
          userClass: 1,
          status: 3,
          uploaded: 30 * 1024 * 1024 * 1024, // 30GB
          downloaded: 80 * 1024 * 1024 * 1024, // 80GB
          shareRatio: 0.375,
          bonusPoints: 120,
          passkey: 'xxx',
          createdTime: '2024-01-15T10:00:00',
          lastLoginTime: '2024-02-10T15:30:00',
          lastLoginIp: '192.168.1.1',
          avatar: '',
          signature: '',
          assessmentDeadline: '2024-03-15T00:00:00',
          warningCount: 0
        },
        {
          id: 2,
          username: 'newuser2',
          email: 'newuser2@example.com',
          userClass: 1,
          status: 3,
          uploaded: 60 * 1024 * 1024 * 1024, // 60GB
          downloaded: 40 * 1024 * 1024 * 1024, // 40GB
          shareRatio: 1.5,
          bonusPoints: 200,
          passkey: 'yyy',
          createdTime: '2024-01-20T14:00:00',
          lastLoginTime: '2024-02-11T09:15:00',
          lastLoginIp: '192.168.1.2',
          avatar: '',
          signature: '',
          assessmentDeadline: '2024-03-20T00:00:00',
          warningCount: 0
        },
      ];
      setAssessmentUsers(mockUsers);
    } catch (error) {
      console.error('获取考核用户失败:', error);
      message.error('获取考核用户失败');
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = () => {
    const totalAssessment = assessmentUsers.length;
    const expiringSoon = assessmentUsers.filter(user => {
      // 计算距离考核截止还有多少天，如果少于7天算即将到期
      return true; // 简化计算
    }).length;
    
    const avgProgress = assessmentUsers.length > 0 ? 
      assessmentUsers.reduce((sum, user) => {
        const uploadProgress = Math.min(100, (user.uploaded / (50 * 1024 * 1024 * 1024)) * 100);
        const ratioProgress = Math.min(100, (user.shareRatio / 0.4) * 100);
        return sum + Math.min(100, (uploadProgress + ratioProgress) / 2);
      }, 0) / assessmentUsers.length : 0;

    setStats({ totalAssessment, expiringSoon, avgProgress });
  };

  const checkSingleAssessment = async (userId: number) => {
    try {
      // const result = await checkUserAssessment(userId);
      // message.success(`用户考核检查完成: ${result.data.message}`);
      message.success('考核检查完成');
      fetchAssessmentUsers();
    } catch (error) {
      message.error('考核检查失败');
    }
  };

  const batchCheckAssessments = async () => {
    try {
      setLoading(true);
      // const results = await batchCheckAssessments();
      // setBatchResults(results.data);
      
      // 模拟结果
      const mockResults: AssessmentResult[] = [
        {
          userId: 1,
          username: 'newuser1',
          currentStatus: 3,
          isExpired: false,
          deadline: '2024-02-15T10:00:00',
          daysRemaining: 5,
          uploadRequirementMet: false,
          shareRatioRequirementMet: false,
          currentUploaded: 30 * 1024 * 1024 * 1024,
          requiredUploaded: 50 * 1024 * 1024 * 1024,
          currentShareRatio: 0.375,
          requiredShareRatio: 0.4,
          assessmentResult: 'IN_PROGRESS',
          message: '考核进行中',
        },
      ];
      setBatchResults(mockResults);
      message.success('批量检查完成');
    } catch (error) {
      message.error('批量检查失败');
    } finally {
      setLoading(false);
    }
  };

  const setAssessment = async (values: any) => {
    if (!selectedUser) return;
    
    try {
      // await setUserAssessment(selectedUser.id, values.assessmentDays);
      message.success('考核期设置成功');
      setModalVisible(false);
      fetchAssessmentUsers();
    } catch (error) {
      message.error('考核期设置失败');
    }
  };

  const cancelAssessment = async (userId: number) => {
    try {
      // await cancelUserAssessment(userId);
      message.success('考核已取消');
      fetchAssessmentUsers();
    } catch (error) {
      message.error('取消考核失败');
    }
  };

  const getOverallProgress = () => {
    return assessmentUsers.length > 0 ?
      assessmentUsers.reduce((sum, user) => {
        const uploadProgress = Math.min(100, (user.uploaded / (50 * 1024 * 1024 * 1024)) * 100);
        const shareRatio = user.shareRatio ?? 0;
        const ratioProgress = Math.min(100, (shareRatio / 0.4) * 100);
        return sum + Math.min(100, (uploadProgress + ratioProgress) / 2);
      }, 0) / assessmentUsers.length : 0;
  };

  const getAssessmentProgress = (user: User) => {
    const uploadProgress = Math.min(100, (user.uploaded / (50 * 1024 * 1024 * 1024)) * 100);
    const shareRatio = user.shareRatio ?? 0;
    const ratioProgress = Math.min(100, (shareRatio / 0.4) * 100);
    const totalProgress = Math.min(100, (uploadProgress + ratioProgress) / 2);
    
    return {
      uploadProgress,
      ratioProgress,
      totalProgress
    };
  };

  const getStatusColor = (status: number) => {
    switch (status) {
      case 3: return 'processing';
      case 1: return 'success';
      case 0: return 'error';
      default: return 'default';
    }
  };

  const columns = [
    {
      title: '用户信息',
      key: 'userInfo',
      render: (record: User) => (
        <Space>
          <UserOutlined />
          <div>
            <div><Text strong>{record.username}</Text></div>
            <div><Text type="secondary">{record.email}</Text></div>
          </div>
        </Space>
      ),
    },
    {
      title: '考核进度',
      key: 'progress',
      render: (record: User) => {
        const { uploadProgress, ratioProgress, totalProgress } = getAssessmentProgress(record);
        return (
          <Space direction="vertical" size="small" style={{ width: '100%' }}>
            <div>
              <Text>总进度:</Text>
              <Progress percent={totalProgress} size="small" />
            </div>
            <Row gutter={8}>
              <Col span={12}>
                <Tooltip title={`${formatBytes(record.uploaded)} / 50GB`}>
                  <Progress
                    percent={uploadProgress}
                    size="small"
                    strokeColor="#52c41a"
                    format={() => '上传'}
                  />
                </Tooltip>
              </Col>
              <Col span={12}>
                <Tooltip title={`${record.shareRatio?.toFixed(2) ?? '0.00'} / 0.40`}>
                  <Progress
                    percent={ratioProgress}
                    size="small"
                    status={ratioProgress >= 100 ? 'success' : 'active'}
                  />
                </Tooltip>
              </Col>
            </Row>
          </Space>
        );
      },
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={getStatusColor(status)}>
          {status === 3 ? '考核中' : status === 1 ? '正常' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '注册时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      render: (time: string) => formatDateTime(time),
    },
    {
      title: '操作',
      key: 'actions',
      render: (record: User) => (
        <Space>
          <Button 
            size="small" 
            type="primary"
            onClick={() => checkSingleAssessment(record.id)}
          >
            检查考核
          </Button>
          <Button
            size="small"
            onClick={() => {
              setSelectedUser(record);
              setModalVisible(true);
              form.setFieldsValue({ assessmentDays: 30 });
            }}
          >
            设置考核期
          </Button>
          <Popconfirm
            title="确定要取消此用户的考核吗？"
            onConfirm={() => cancelAssessment(record.id)}
          >
            <Button size="small" danger>
              取消考核
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Title level={2}>用户考核管理</Title>
      
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={8}>
          <Card>
            <Statistic
              title="考核期用户"
              value={stats.totalAssessment}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="即将到期"
              value={stats.expiringSoon}
              prefix={<ExclamationCircleOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="平均进度"
              value={stats.avgProgress}
              precision={1}
              suffix="%"
              prefix={<CalendarOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 操作按钮 */}
      <Card style={{ marginBottom: 16 }}>
        <Space>
          <Button 
            type="primary" 
            loading={loading}
            onClick={batchCheckAssessments}
          >
            批量检查考核
          </Button>
          <Button onClick={fetchAssessmentUsers}>
            刷新列表
          </Button>
        </Space>
      </Card>

      {/* 考核用户表格 */}
      <Card title="考核期用户列表">
        <Table
          columns={columns}
          dataSource={assessmentUsers}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      {/* 批量检查结果 */}
      {batchResults.length > 0 && (
        <Card title="批量检查结果" style={{ marginTop: 16 }}>
          <Table
            dataSource={batchResults}
            rowKey="userId"
            pagination={false}
            columns={[
              {
                title: '用户',
                dataIndex: 'username',
                key: 'username',
              },
              {
                title: '考核结果',
                dataIndex: 'assessmentResult',
                key: 'assessmentResult',
                render: (result: string) => {
                  const color = result === 'PASSED' ? 'success' : 
                              result === 'FAILED' ? 'error' : 'processing';
                  const icon = result === 'PASSED' ? <CheckCircleOutlined /> :
                              result === 'FAILED' ? <CloseCircleOutlined /> : 
                              <ExclamationCircleOutlined />;
                  return (
                    <Tag color={color} icon={icon}>
                      {result === 'PASSED' ? '通过' : 
                       result === 'FAILED' ? '失败' : '进行中'}
                    </Tag>
                  );
                },
              },
              {
                title: '详情',
                dataIndex: 'message',
                key: 'message',
              },
            ]}
          />
        </Card>
      )}

      {/* 设置考核期模态框 */}
      <Modal
        title="设置考核期"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
      >
        {selectedUser && (
          <Form form={form} onFinish={setAssessment} layout="vertical">
            <Form.Item label="用户">
              <Text strong>{selectedUser.username}</Text>
            </Form.Item>
            
            <Form.Item
              label="考核天数"
              name="assessmentDays"
              rules={[{ required: true, message: '请输入考核天数' }]}
            >
              <InputNumber
                min={1}
                max={90}
                placeholder="请输入考核天数"
                style={{ width: '100%' }}
              />
            </Form.Item>
            
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  设置
                </Button>
                <Button onClick={() => setModalVisible(false)}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        )}
      </Modal>
    </div>
  );
};

export default UserAssessment; 